package org.mushroomdb.security.queries;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import org.mushroomdb.catalog.Catalog;
import org.mushroomdb.catalog.Table;
import org.mushroomdb.engine.EvaluationEngine;
import org.mushroomdb.exception.EvaluationEngineException;
import org.mushroomdb.exception.RDBMSRuntimeException;
import org.mushroomdb.query.Query;
import org.mushroomdb.security.Privilege;
import org.mushroomdb.security.SecurityService;
import org.mushroomdb.security.User;
import org.mushroomdb.service.ServiceManager;


public class RevokeQuery extends SecurityQuery {
    private String tableName;
    private List privilegesRevoked;
    private String userName;
    
    /**
     * @param queryString
     */
    public RevokeQuery(String queryString) {
        
    	this.privilegesRevoked = new LinkedList();
    	
        String query = queryString.replaceAll("," , " ");
        String [] keyWords = query.split(" ");
        List keyWordsList = new ArrayList();
        for(int i=0; i < keyWords.length; i++){
            String word = keyWords[i].trim();
            keyWordsList.add(word);
        }
        
        int onIndex = keyWordsList.indexOf("ON");
        if(onIndex != -1)
            this.tableName = (String) keyWordsList.get(onIndex +1);
        
        int fromIndex = keyWordsList.indexOf("FROM");
        if(fromIndex != -1)
            this.userName = (String) keyWordsList.get(fromIndex +1);
        
        int privilegesFrom;
        if(keyWordsList.contains("GRANT")){
            privilegesFrom = keyWordsList.indexOf("FOR")+1;
            Privilege privilege = new Privilege("GRANT");
            this.privilegesRevoked.add(privilege);
        }
        else{
            privilegesFrom = 1;
        }
        
        for(int i= privilegesFrom; i < onIndex; i++){
            String word = (String) keyWordsList.get(i);
            Privilege privilege = new Privilege(word);
            this.privilegesRevoked.add(privilege);
        }
       
    }
    
    public Object execute(EvaluationEngine evaluationEngine) {
        SecurityService service = (SecurityService) ServiceManager
                .getInstance().getService(SecurityService.class);
        Catalog catalog = Catalog.getInstance();

        User user = null;
        user = service.getUserByName(this.userName);
        Table table = catalog.getTableByName(this.tableName);
        Iterator iter = this.privilegesRevoked.iterator();
        while (iter.hasNext()) {
            Privilege privilege = (Privilege) iter.next();
            service.revoke(user, privilege, table);
        }

        //return qty of privilege granted
        return user;

    }
}
